import initState from './initState'
import { mainStates } from '@/store/type'
import { MutationPayload } from 'vuex'
import { initVuex } from 'lib-plugins/store'
import { deepClone } from 'lib-utils'
import { initGlobalState } from 'qiankun'
import { useDebounceFn } from '@vueuse/core'


const store = initVuex<mainStates>({
  ...initState
})
let prevState: mainStates = deepClone(store.state)

// 主应用创建共享状态：
const { onGlobalStateChange, setGlobalState } = initGlobalState({
  ...prevState.common
})

onGlobalStateChange((value: Record<string, any>, prev: Record<string, any>) => {
  store.commit('setCommonStore', {
    ...value
  })
})
// 当 store 初始化后调用
store.subscribe((mutation: MutationPayload, state: mainStates) => {
  // 每次 mutation 之后调用
  const nextState: mainStates = deepClone(state)
  if (JSON.stringify(nextState) !== JSON.stringify(prevState)) {
    prevState = nextState
    // 微应用中store变更后，将状态更新到主应用
    setGlobalState &&
      setGlobalState({ ...state.common })
  }
})


export default store
